<template>
	<view class="view" v-if="Ok">
		<communityList @likesClick="likesClick" @details="getdetails" :key="key" @info="getInfo" :publishId="publishId" type="2" />
		<!-- 打赏信息 -->
		<view class="reward-box">
			<view class="reward-btn" @click="showReward = true">打赏</view>
			<view v-if="rewardList.length > 0" class="reward-list">
				<image v-for="(item, index) in rewardList" :key="index" class="reward-avatar" :src="item.avatar || '/static/images/default_avatar.png'" mode="aspectFill"></image>
			</view>
		</view>
		<!-- 评论列表 -->
		<view class="discussbox" v-if="list.length > 0">
			<p class="title">
				<span>全部评论</span>
				<span>（{{ commentNum }}条）</span>
			</p>
			<view class="item" v-for="(item, index) in list" :key="index" @click.stop="replyComment(item)">
				<view class="userInfo">
					<image :src="item.avatar || '/static/images/default_avatar.png'" mode="aspectFill"></image>
					<view>
						<p>{{ item.nickName || '' }}</p>
						<p>{{ item.createTime }}</p>
					</view>
					<view v-if="item.isAdoption == 1" class="solution">已采纳</view>
					<view v-else-if="showAdopt" class="adopt" @click.stop="adoptComment(item.id)">采纳</view>
				</view>
				<view class="details">
					<p>{{ item.commentDetail }}</p>
					<view class="imgList" v-show="item.imgList.length > 0">
						<image @click.stop="preview(val, item.imgList)" v-for="(val, k) in item.imgList" :key="k" :src="val" mode="aspectFill"></image>
					</view>
				</view>
				<view class="bottom">
					<view class="comment">
						<image src="/static/images/ic_comment.png" />
						<view>{{ item.replies || 0 }}</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 评论回复 -->
		<view class="dialog" v-if="showReply">
			<view class="mask" @click.prevent></view>
			<view class="content">
				<view class="title">
					<view>全部回复</view>
					<icon type="cancel" color="#999999" @click.stop="showReply = false"></icon>
				</view>
				<scroll-view class="list" scroll-y @scrolltolower="getReplyList()">
					<view class="item" v-for="(item, index) in replyList" :key="index">
						<view class="userInfo">
							<image :src="item.avatar || '/static/images/default_avatar.png'" mode="aspectFill"></image>
							<view>
								<p>{{ item.nickName || '' }}</p>
								<p>{{ item.createTime }}</p>
							</view>
						</view>
						<view class="details">
							<p>{{ item.commentDetail }}</p>
							<view class="imgList" v-show="item.imgList.length > 0">
								<image @click.stop="preview(val, item.imgList)" v-for="(val, k) in item.imgList" :key="k" :src="val" mode="aspectFill"></image>
							</view>
						</view>
					</view>
				</scroll-view>
				<view class="comment-box" @click.stop="sendBox = true">@楼主</view>
			</view>
		</view>
		<!-- 评论框输入框 -->
		<view @click.prevent class="mark" v-show="sendBox" @click.stop="sendBox = false">
			<view class="Box" @click.stop>
				<view class="left">
					<textarea :fixed="true" v-model.trim="commentDetail" placeholder="回复楼主(不能超过300字哦)" maxlength="300" cursor-spacing="50"></textarea>
					<image class="selectImg" @click="chooseImg" src="/static/images/uploadn.png" v-if="tempFilePaths.length < 5" mode="aspectFill"></image>

					<view class="preview" v-if="tempFilePaths.length > 0">
						<view class="item" v-for="(item, index) in tempFilePaths" :key="index">
							<image class="item-image" @click="preview(item, tempFilePaths)" :src="item" />
							<image class="close" @click="del(index)" src="/static/images/detele.png" />
						</view>
					</view>
				</view>
				<view @click.stop="send">发送</view>
			</view>
		</view>
		<!-- 评论外边框 -->
		<view class="tabbar">
			<view @click="sendBox = true">@楼主</view>
			<view>
				<image src="/static/images/ic_comment.png"></image>
				<view>{{ commentNum }}</view>
			</view>
			<!-- 收藏-->
			<view>
				<image v-if="!details.collectStatus" @click="like(1)" src="/static/images/ic_like.png"></image>
				<image @click="like(2)" v-else src="/static/images/ic_like_active.png"></image>
			</view>
			<!-- 点赞 -->
			<view>
				<image v-if="details.status" @click="postLike(2)" src="/static/images/ic_praise_active.png"></image>
				<image @click="postLike(1)" v-else src="/static/images/ic_praise.png"></image>
			</view>
		</view>
		<!-- 打赏弹窗 -->
		<view class="dialog" v-if="showReward">
			<view class="mask" @click.prevent></view>
			<view class="input-content">
				<view class="title">打赏</view>
				<input v-model="rewardValue" placeholder="请输入打赏积分" type="number" />
				<view class="operate">
					<view @click.stop="showReward = false">取消</view>
					<view @click.stop="reward()">确定</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import {
	getCommentList,
	postLike,
	noLike,
	postCollection,
	postDelete,
	commentsPost,
	policy, //oss签名文件
	getPublishInfoDetails,
	addBrowserHistory
} from '@/apis/request.js';
import communityList from '@/components/communityList.vue';

export default {
	components: {
		communityList
	},
	data() {
		return {
			Ok: false,
			sendBox: false,
			publishId: '', //帖子id
			list: [],
			finished: false,
			pageNo: 1,
			commentNum: 0,
			info: {},
			key: 1, //改变key以便让子组件重新渲染
			commentDetail: '',
			details: null,
			tempFilePaths: [], //临时图片数组
			index: 0, //记录上传图片下标
			imgList: [], //最终上传完成的图片数组
			formParam: {},
			params: {},
			loginUserId: null,
			showAdopt: false,
			showReply: false,
			replyFinished: false,
			replyObject: {},
			replyList: [],
			replyPageNo: 1,
			showReward: false,
			rewardValue: null,
			rewardList: []
		};
	},
	onLoad(options) {
		this.publishId = options.id;
		this.getpolicy();
		this.getInfoDetails();
		this.sendBox = false;
		this.getCommentList();
		if (uni.getStorageSync('token')) {
			this.addRecord();
		}
	},
	onShow() {
		this.loginUserId = uni.getStorageSync('userInfo').id || null;
	},
	methods: {
		addRecord() {
			//添加浏览记录
			addBrowserHistory({
				type: 1,
				objectId: this.publishId
			}).then(res => {});
		},
		// 子组件点赞 刷新
		likesClick(type) {
			this.postLike(type);
		},
		// 获取详情信息
		async getInfoDetails() {
			this.details = await getPublishInfoDetails({
				publishId: this.publishId
			});
			this.rewardList = this.details.rewardList || [];
			this.showAdopt = this.details.publishType == 1 && this.details.helpStatus == 0 && this.details.userId == this.loginUserId;
			this.Ok = true;
		},
		//获取签名文件；上传文件用
		async getpolicy() {
			this.params = await policy();
		},
		del(index) {
			this.$dialog('提示', '是否确认删除').then(res => {
				this.tempFilePaths.splice(index, 1);
				this.imgList.splice(index, 1);
				this.index--;
			});
		},
		chooseImg() {
			//选择图片
			wx.chooseImage({
				count: 5,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: res => {
					// tempFilePath可以作为img标签的src属性显示图片
					// const tempFilePaths = res.tempFilePaths;
					this.tempFilePaths.push(...res.tempFilePaths);
					//选择完毕上传图片
					this.uploadImg(this.tempFilePaths);
					wx.showLoading({
						title: '上传图片中...',
						mask: true
					});
				}
			});
		},
		//上传图片
		uploadImg(file) {
			let { host, dir, accessKeyId, policy, signature } = this.params;
			const aliyunFileKey = dir + '/' + Math.floor(Math.random() * 150) + '.png';
			const formParam = {
				key: aliyunFileKey,
				policy: policy,
				OSSAccessKeyId: accessKeyId,
				signature: signature,
				success_action_status: '200'
			};
			uni.uploadFile({
				url: host, //仅为示例，非真实的接口地址
				filePath: file[this.index],
				name: 'file',
				formData: formParam,
				success: res => {
					if (res.statusCode != 200) {
						this.$Toast(`上传出错${JSON.stringify(res)}`);
						return;
					}
					let data = host + '/' + aliyunFileKey;
					this.imgList.push(data);
					this.index++;
					if (this.index < file.length) {
						//  小于说明还未上传完成
						this.uploadImg(file);
					} else {
						//上传完成
						wx.hideLoading();
						wx.showToast({
							title: '图片上传完成',
							icon: 'none',
							duration: 2000
						});
					}
				},
				fail: err => {
					// 图片上传失败
					wx.hideLoading();
					this.$dialog('提示', `第${this.index + 1}张图片上传失败，是否重新上传`)
						.then(res => {
							//用户点击确定，重新上传该图
							this.uploadImg(file);
						})
						.catch(err => {
							this.tempFilePaths.splice(this.index, 1);
							if (this.index < this.tempFilePaths.length) {
								wx.showLoading({
									title: '继续上传...',
									mask: true,
									success: res => {
										this.index++;
										this.uploadImg(file);
									}
								});
							} else {
								this.index = 0;
								wx.showToast({
									title: '图片上传完成',
									icon: 'none',
									duration: 2000
								});
							}
						});
				}
			});
		},
		preview(current, imgList) {
			this.$Imgpreview(current, imgList);
		},
		send() {
			if (this.commentDetail == '') {
				this.$Toast('请输入回复内容');
			} else if (this.showReply) {
				//回复评论
				this.$api.http(
					'/group/publishInfo/replyToComments',
					'POST',
					{
						imageUrl: this.imgList.toString(),
						commentDetail: this.commentDetail,
						commentatorId: uni.getStorageSync('userInfo').id,
						publishId: this.details.id,
						superiorId: this.replyObject.id
					},
					res => {
						this.sendBox = false;
						this.commentDetail = '';
						this.imgList = '';
						this.key++;
						this.replyFinished = false;
						this.replyPageNo = 1;
						this.replyList = [this.replyObject];
						this.getReplyList();
					}
				);
			} else {
				const details = this.details;
				var publishComment = {
					imageUrl: this.imgList.toString(),
					commentDetail: this.commentDetail,
					commentatorId: uni.getStorageSync('userInfo').id,
					publishId: details.id
				};
				const parmas = JSON.stringify(publishComment);
				commentsPost(publishComment).then(res => {
					this.sendBox = false;
					this.commentDetail = '';
					this.imgList = '';
					this.key++;
					this.finished = false;
					this.pageNo = 1;
					this.list = [];
					this.getCommentList();
				});
			}
		},
		like(type) {
			// 1收藏,2取消收藏
			if (type == '1') {
				postCollection({
					publishId: this.details.id
				}).then(res => {
					this.key++;
					this.getInfoDetails();
				});
			} else {
				this.$dialog('提示', '是否取消收藏').then(res => {
					postDelete({
						publishId: this.details.id
					}).then(res => {
						this.key++;
						this.getInfoDetails();
					});
				});
			}
			uni.$emit('change')
		},
		postLike(type) {
			// 1点赞,2取消点赞
			if (type == '1') {
				postLike({
					publishId: this.details.id
				}).then(res => {
					this.key++;
					this.getInfoDetails();
				});
			} else {
				this.$dialog('提示', '是否取消点赞').then(res => {
					noLike({
						publishId: this.details.id
					}).then(res => {
						this.key++;
						this.getInfoDetails();
					});
				});
			}
		},
		async getCommentList() {
			if (!this.finished) {
				const data = await getCommentList({
					pageNo: this.pageNo++,
					pageSize: 10,
					publishId: this.publishId
				});
				this.commentNum = data.total;
				if (data.records.length == 0) {
					this.finished = true;
				}
				this.list = this.list.concat(
					...data.records.map(item => {
						return {
							...item,
							imgList: item.imageUrl ? item.imageUrl.split(',') : []
						};
					})
				);
				uni.stopPullDownRefresh();
			}
		},
		//自定义组件
		getInfo(e) {
			this.info = e;
		},
		getdetails(e) {
			this.details = e;
		},
		adoptComment(id) {
			const that = this;
			uni.showModal({
				title: '提示',
				content: '您确定采纳该评论吗？',
				success(res) {
					if (res.confirm) {
						that.$api.http(
							'/group/publishInfo/helpCommentAdoption',
							'GET',
							{
								commentId: id
							},
							res => {
								that.finished = false;
								that.pageNo = 1;
								that.list = [];
								that.getInfoDetails();
								that.getCommentList();
							}
						);
					}
				}
			});
		},
		replyComment(item) {
			console.log(item);
			this.showReply = true;
			this.replyObject = item;
			this.replyFinished = false;
			this.replyPageNo = 1;
			this.replyList = [item];
			this.getReplyList();
		},
		getReplyList() {
			if (!this.replyFinished) {
				this.$api.http(
					'/group/publishInfo/api/n/getReplyList',
					'GET',
					{
						commentId: this.replyObject.id,
						pageNo: this.replyPageNo++,
						pageSize: 10
					},
					res => {
						if (res.data.result.records.length == 0) {
							this.replyFinished = true;
						}
						this.replyList = this.replyList.concat(
							res.data.result.records.map(item => {
								return {
									...item,
									imgList: item.imageUrl ? item.imageUrl.split(',') : []
								};
							})
						);
					}
				);
			}
		},
		reward() {
			if (this.rewardValue) {
				this.$api.http(
					'/group/publishInfo/postRewards',
					'GET',
					{
						amount: this.rewardValue,
						publishId: this.publishId,
						userId: uni.getStorageSync('userInfo').id
					},
					res => {
						if (res.data.code == 200) {
							this.$Toast('打赏成功');
							this.showReward = false;
							this.rewardValue = null;
							this.getInfoDetails();
						} else if (res.data.code == 4002) {
							this.showReward = false;
							this.rewardValue = null;
							uni.showModal({
								title: '积分不足',
								content: '是否前往充值积分？',
								confirmText: '充值',
								success(res) {
									if (res.confirm) {
										// 前往充值界面
										uni.navigateTo({
											url: '/pages/other/deposit/deposit'
										});
									}
								}
							});
						} else {
							this.$Toast(res.data.message || '打赏失败，请重试！');
						}
					}
				);
			} else {
				this.$Toast('请输入打赏积分');
			}
		}
	},
	onReachBottom() {
		this.getCommentList();
	},
	onPullDownRefresh() {
		this.finished = false;
		this.pageNo = 1;
		this.list = [];
		this.getInfoDetails();
		this.getCommentList();
	},
	onShareAppMessage() {
		const id = this.publishId;
		const title = this.details.publishContent;
		return {
			title: title,
			imageUrl: this.$shareImageUrl,
			path: 'pages/CommunityPages/details/main?id=' + id
		};
	}
};
</script>

<style lang="less" scoped>
.view {
	background-color: #f1efef;
	height: calc(100vh - 44px);

	.reward-box {
		padding: 20rpx;
		margin-top: -2rpx;
		background-color: #ffffff;

		.reward-btn {
			width: 100rpx;
			height: 40rpx;
			line-height: 40rpx;
			margin: 0 auto;
			margin-bottom: 10rpx;
			text-align: center;
			border-radius: 20rpx;
			color: #ffffff;
			font-size: 24rpx;
			background-color: #32C59A;
		}

		.reward-list {
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: center;
			flex-wrap: wrap;
			padding: 5rpx;
			background-color: #ffffff;

			.reward-avatar {
				width: 50rpx;
				height: 50rpx;
				border-radius: 50%;
				margin: 5rpx;
			}
		}
	}

	.discussbox {
		margin-top: 30rpx;
		padding: 0rpx 30rpx;
		background-color: #ffffff;
		border-bottom: 120upx solid #f1efef;

		.title {
			display: flex;
			height: 80rpx;
			border-bottom: 1rpx solid #f1f1f1;
			align-items: center;

			span:nth-child(1) {
				font-size: 28rpx;
			}

			span:nth-child(2) {
				font-size: 28rpx;
				color: #999999;
			}
		}

		.item {
			padding: 30rpx 0rpx;
			border-bottom: 1rpx solid #f1f1f1;

			&:last-child {
				border-bottom: none;
			}

			.userInfo {
				position: relative;
				display: flex;
				align-items: center;

				image {
					width: 80rpx;
					height: 80rpx;
					margin-right: 20rpx;
					border-radius: 50%;
				}

				view {
					p:nth-child(1) {
						font-size: 30rpx;
					}

					p:nth-child(2) {
						font-size: 26rpx;
						color: #999999;
					}
				}

				.solution {
					position: absolute;
					right: 0;
					color: #ff290b;
					font-size: 26rpx;
					font-weight: bold;
					transform: rotate(45deg);
				}

				.adopt {
					position: absolute;
					right: 0;
					text-align: center;
					width: 80rpx;
					height: 40rpx;
					line-height: 40rpx;
					color: #32C59A;
					border-radius: 20rpx;
					font-size: 26rpx;
					border: 1rpx solid #32C59A;
				}
			}

			.details {
				margin-top: 30rpx;
				color: #333333;

				p {
					margin-bottom: 20rpx;
					word-break: break-all;
				}

				img {
					width: 222rpx;
					height: 222rpx;
					border-radius: 10rpx;
					margin: 10rpx 10rpx 10rpx 0rpx;
				}
			}

			.bottom {
				width: 100%;
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: flex-end;

				.comment {
					display: flex;
					flex-direction: row;
					align-items: center;
					justify-content: center;
					font-size: 28rpx;
					color: #666666;

					image {
						width: 30rpx;
						height: 30rpx;
						margin-right: 10rpx;
					}
				}
			}
		}
	}

	.tabbar {
		position: fixed;
		bottom: 0;
		height: 115rpx;
		display: flex;
		align-items: center;
		padding: 0rpx 30rpx;
		background-color: #ffffff;
		width: 100%;

		view:nth-child(1) {
			width: 406rpx;
			height: 65rpx;
			line-height: 65rpx;
			background: #f2f2f2;
			border: 1px solid #dcdcdc;
			border-radius: 33rpx;
			padding-left: 10rpx;
			font-size: 29rpx;
			color: #999999;
			margin-right: 45rpx;
		}

		image {
			width: 36rpx;
			height: 36rpx;
		}

		view:nth-child(2) {
			position: relative;

			view {
				width: 30rpx;
				height: 30rpx;
				line-height: 30rpx;
				text-align: center;
				font-size: 20rpx;
				background: #f24c41;
				border-radius: 50%;
				color: #ffffff;
				position: absolute;
				top: -18rpx;
				right: -10rpx;
				z-index: 1;
			}
		}

		view:nth-last-child(2) {
			margin: 0rpx 53rpx;
		}
	}

	.mark {
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 1000;
		top: 0;
		left: 0;
		position: fixed;
		width: 100%;
		height: 100%;

		.Box {
			background-color: #ffffff;
			display: flex;
			flex-direction: row;
			position: absolute;
			bottom: 0;
			width: calc(100% - 60rpx);
			z-index: 20;
			align-items: flex-end;
			padding: 30rpx;

			.left {
				background: #f2f2f2;
				border: 2rpx solid #dcdcdc;
				border-radius: 33rpx;
				padding: 20rpx;
				flex: 1;

				textarea {
					border: none;
					height: 60rpx;
					width: 100%;
					font-size: 22rpx;
				}
			}

			view:nth-child(2) {
				text-align: center;
				width: 100rpx;
				font-size: 30rpx;
				color: #32C59A;
			}
		}
	}

	.selectImg {
		width: 100rpx;
		height: 100rpx;
	}

	.preview {
		display: flex;
		flex-direction: row;
		align-items: center;
		flex-wrap: wrap;
		margin-top: 20rpx;

		.item {
			position: relative;
			width: 170rpx !important;
			margin: 10rpx 10rpx 0rpx 0rpx;

			.item-image {
				width: 170rpx;
				height: 170rpx;
				border-radius: 10rpx;
			}

			.close {
				position: absolute;
				top: 0;
				right: 0;
				width: 44rpx;
				height: 44rpx;
			}
		}
	}

	.dialog {
		position: fixed;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		z-index: 99;

		.mask {
			position: absolute;
			z-index: 9;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, 0.5);
		}

		.content {
			position: absolute;
			display: flex;
			flex-direction: column;
			bottom: 0;
			z-index: 99;
			width: 100%;
			height: 80vh;
			background-color: #ffffff;
			border-radius: 30rpx 30rpx 0 0;

			.title {
				padding: 20rpx;
				display: flex;
				flex-direction: row;
				justify-content: space-between;
			}

			.list {
				height: calc(80vh - 176rpx);

				.item {
					margin-left: 50rpx;
					padding: 20rpx 30rpx;
					border-bottom: 1rpx solid #f1f1f1;

					&:first-child {
						margin-left: 0rpx;
					}

					.userInfo {
						position: relative;
						display: flex;
						align-items: center;

						image {
							width: 80rpx;
							height: 80rpx;
							margin-right: 20rpx;
							border-radius: 50%;
						}

						view {
							p:nth-child(1) {
								font-size: 30rpx;
							}

							p:nth-child(2) {
								font-size: 26rpx;
								color: #999999;
							}
						}
					}

					.details {
						margin-top: 30rpx;
						color: #333333;

						p {
							margin-bottom: 20rpx;
							word-break: break-all;
						}

						image {
							width: 222rpx;
							height: 222rpx;
							border-radius: 10rpx;
							margin: 10rpx 10rpx 10rpx 0rpx;
						}
					}
				}
			}

			.comment-box {
				width: calc(100% - 80rpx);
				height: 70rpx;
				line-height: 70rpx;
				padding: 0 20rpx;
				margin: 10rpx 20rpx;
				font-size: 26rpx;
				color: #999999;
				background-color: #f1f1f1;
				border-radius: 35rpx;
			}
		}

		.input-content {
			position: absolute;
			display: flex;
			flex-direction: column;
			top: calc(50vh - 300rpx);
			left: 125rpx;
			z-index: 99;
			width: 500rpx;
			background-color: #ffffff;
			border-radius: 30rpx;

			.title {
				height: 100rpx;
				line-height: 100rpx;
				text-align: center;
				font-size: 32rpx;
				color: #333333;
			}

			input {
				margin: 0 30rpx 30rpx 30rpx;
				background-color: #f1f1f1;
				padding: 10rpx 25rpx;
				font-size: 28rpx;
				border-radius: 30rpx;
			}

			.operate {
				display: flex;
				flex-direction: row;
				border-top: 1rpx solid #f1f1f1;

				view {
					flex: 1;
					height: 88rpx;
					line-height: 88rpx;
					text-align: center;
					color: #32C59A;
					font-size: 28rpx;

					&:first-child {
						color: #333333;
						border-right: 1rpx solid #f1f1f1;
					}
				}
			}
		}
	}
}
</style>
